import http from 'http'
import SocketIo from "socket.io"
import {Models} from "../../common/typings/model"
export default class SocketService {
    public plays: Models.Player[] = []
    public socket!: SocketIo.Socket
    constructor(server: http.Server){
        const io = new SocketIo.Server(server, {
            allowEIO3: true,
            cors: {
                // origin: config.clientURL,
                origin: '*',
                // methods: ["GET", "POST"],
                credentials: true,
            }
        })
        // const io = require('socket.io')(this.server);
        io.on('connection', (socket: SocketIo.Socket) => {
            console.log('socket初始化完成');
            // socket.on('disconnect', () => {
            //     console.log('user 断开连接');
            //     this.plays = this.plays.filter((u:Models.Player) => {
            //         return u.socketId !== socket.id
            //     })
            // });
            // socket.on('login', (data: Models.SocketMessageData) => {
            //     let user = data.user
            //     let index = this.plays.findIndex((u: Models.Player) => {
            //         return user.id === u.id
            //     })
            //     if(index === -1){
            //         this.plays.push({...user,socketId: socket.id})
            //     }
                
            //     console.log(user)
            // });

            socket.on('message', this.handle(this.messageListen,socket) as any)
            socket.on('login', this.handle(this.messageListen,socket) as any)
            socket.on('userSay', this.handle(this.userLogin,socket) as any)
            socket.on('disconnect', this.handle(this.userDisconnect,socket) as any)

 
           
            socket.emit('serverSay',{hello: '链接成功'})
        })
    }
    public handle(listener: Function,socket: SocketIo.Socket): Function {
        console.log('socket.id:',socket.id)
        socket.emit('message', {hello: '服务端已收到'})
        return listener.bind(this,socket)
    }


    public userSayListen(socket: SocketIo.Socket,data: Models.SocketMessageData){
        console.log(`用户-${data.user.nickName}-${socket.id}说：`,data)
        
    }
    public messageListen(socket: SocketIo.Socket,data: Models.SocketMessageData){
        console.log('message',data)
    }

    public userLogin(socket: SocketIo.Socket,data: Models.SocketMessageData){
        let user = data.user
        let index = this.plays.findIndex((u: Models.Player) => {
            return user.id === u.id
        })
        if(index === -1){
            this.plays.push({...user,socketId: socket.id})
        }
        socket.emit('serverSay',{hello: '登录成功'})
        console.log(user)
    }

    public userDisconnect(socket: SocketIo.Socket){
        console.log(`user-${socket.id} 断开连接`);
        this.plays = this.plays.filter((u:Models.Player) => {
            return u.socketId !== socket.id
        })
    }
}

